import { defineStore } from 'pinia'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

export const useUserStore = defineStore('useUserStore', {
  actions: {
    async logout (){
      const res = await axios.post("/api/user/logout")
      if (res.data.code === 0){
        this.$reset()
      }
      this.isLogin = false
    },
    async login(form: any){
      const res = await axios.post("/api/user/login",form)
      if (res.data.code === 0){
        const user = res.data.data
        ElMessage.success("登录成功")
        this.isLogin = true
        this.id = user.id
      }else {
        ElMessage.error("登录失败")
      }
    },
    async register(form:any){
      const res = await axios.post("/api/user/register",form)
      const router = useRouter()
      if (res.data.code === 0){
        ElMessage.success("注册成功")
        router.push("/")
      }else {
        ElMessage.error("注册失败",res.data.message)
      }
    }
  },
  state: () => {
    return {
      id: 0,
      isLogin: false,
      toke: ''
    }
  },
  persist: true
})
